﻿using System;
using CloudShot.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CloudShot.Utils.Converters
{
  public class HotkeyJsonConverter : JsonConverter
  {
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
      Hotkey hotkey = Hotkey.Empty;

      if (value is Hotkey)
        hotkey = (Hotkey)value;

      writer.WriteValue(hotkey.ToString());
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
      if (!CanConvert(objectType))
        return null;

      Hotkey resultHotkey;

      JToken jValue = JToken.Load(reader);
      var hotkeyStr = jValue.Value<string>();
      Hotkey.TryParse(hotkeyStr, out resultHotkey);

      return resultHotkey;
    }

    public override bool CanConvert(Type objectType)
    {
      return objectType == typeof(Hotkey) || objectType.IsAssignableFrom(typeof(Hotkey));
    }
  }
}